/**
 * @description 数字输入框
 * @author gf
 */

import { Input, InputProps } from 'antd'
import styled from 'styled-components'
import _Number from './utils'
import { validateInput } from '@/utils/utils'
import { useEffect, useState } from 'react'

/**
 *
 * @param unit 单位
 * @param value 原数据
 * @description 日：整数，年：一位小数，其他：两位小数
 */
export const FormatNumber = (unit: string, value: string) => {
  if (unit === '日') {
    return value
  }
}

const InputWrapper = styled.div`
  width: 80px;
  margin: 0 8px;
  .ant-input-affix-wrapper {
    padding: 0 0 0 8px;
    border-color: ${(props) =>
      props.isError ? '#E64A00' : '#D4D7DD'} !important;
    .ant-input-suffix {
      opacity: 0.4;
    }
  }
  .ant-input {
    height: 28px;
    border-color: ${(props) =>
      props.isError ? '#E64A00' : '#D4D7DD'} !important;

    .ant-input {
      height: 27px;
      line-height: 27px;
      padding: 0 8px;
    }
  }
`

interface NewInputNumberProps extends InputProps {
  isError?: boolean // 用来校验为空时的样式
  min?: number // 最小值
  max?: number // 最大值
  precision?: number // 数值精度
}

const SInputNumber = (props: NewInputNumberProps) => {
  const { onChange, min, precision, max } = props
  const [curValue, setCurValue] = useState<number | string | null>()
  let newProps = { ...props }
  delete newProps.isError
  delete newProps.style

  const onChangeNumber = (e) => {
    // 处理后的值
    const res = validateInput(e.target.value, precision, min, max)
    if (curValue?.toString() !== res?.toString()) {
      onChange(res)
    }
    setCurValue(curValue)
  }

  const onBlurNumber = (e) => {
    const res = validateInput(e.target.value, precision, min)
    if (
      res &&
      res?.length > 1 &&
      res.toString().indexOf('.') === res.toString().length - 1
    ) {
      onChange(_Number.toNumber(res))
    }
  }

  useEffect(() => {
    setCurValue(props.value)
  }, [props.value])

  return (
    <InputWrapper isError={props.isError} style={props.style}>
      <Input {...newProps} onChange={onChangeNumber} onBlur={onBlurNumber} />
    </InputWrapper>
  )
}

export default SInputNumber
